<template>
  <div>
    <div class="search-wrap dep-search">
      <div class="common-search ym-box">
        <el-form :model="queryForm" inline @submit.prevent>
          <el-form-item class="w-auto">
            <search-input
              v-model="queryForm.name"
              placeholder="输入科室/部门名称精确查询"
              @search="search"
            />
          </el-form-item>
        </el-form>
      </div>
      <el-button v-if="dep.did" type="primary" class="btn-add" size="small" @click="create"
        >创建科室/部门</el-button
      >
    </div>

    <div class="table-wrap ym-box">
      <ym-table
        v-loading="state.tableLoading"
        :data="state.tableData"
        :column-data="depColumnData"
        :style="{ height: `${tableHeight}px` }"
        :height="tableHeight"
      >
        <template #name="{ row }">
          <div class="cell-name" @click="editInit(row)">{{ row.name }}</div>
        </template>
        <template #status="{ row }">
          <el-switch
            v-model="row.enable"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeStatus(row)"
          />
        </template>
        <!-- <template #status="{ row }">
          <span
            :style="{ color: row.enable ? '#94C106' : '#FF4838' }"
          >{{ row.enable ? '启用' : '禁用' }}</span>
        </template>-->
        <template #contact="{ row }">
          <div class="contact-cell">
            <span class="contact">{{ row.contact }}</span>
            <span v-if="row.contactPhone" class="sperator">|</span>
            <span class="phone">{{ row.contactPhone }}</span>
          </div>
        </template>
        <template #operator="{ row }">
          <el-button type="text" class="btn-edit" @click="editInit(row)">修改</el-button>

          <el-button type="text" class="btn-del" @click="del(row)">删除</el-button>
        </template>
      </ym-table>

      <pagination
        id="page-block"
        v-model:page-num="state.pageObj.pageNum"
        v-model:page-size="state.pageObj.pageSize"
        class="dep-page"
        :total="state.pageObj.total"
        @pagination="search"
      />
    </div>

    <!-- 创建或修改对话框 -->
    <drawer
      v-model:visible="state.dialogVisible"
      :size="500"
      :title="state.dialogTitle"
      @close="closeDrawer"
    >
      <add-or-edit-form
        ref="formWrapper"
        :form="_state.form"
        :is-add="state.isAdd"
        :up-name="dep.name"
        @cancel="handleClose"
        @confirm="confirm"
      />
    </drawer>
  </div>
</template>

<script lang="ts" setup>
import { defineExpose, defineProps, nextTick, reactive, ref, toRefs, useAttrs } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'

import SearchInput from '@/components/CommonSearch/SearchInput/index.vue'
import AddOrEditForm from './AddOrEditForm.vue'

import DepApi from '@/api/backend/dep'

import { getStyle } from '@/utils/dom'
import { depColumnData } from '&/utils/columnData'

import { commonHandle } from '@/views/mixins/common'
import { Drawer, Pagination, YmTable } from '&/mixins/useComponent'
import IBaseObj from '#/index'

const { state, handleAdd, handleEdit, handleClose, handleSearch, handleDelete } = commonHandle()

const props = defineProps({
  dep: {
    type: Object,
    default: () => {},
  },
  oid: {
    type: [String, Number],
    default: '',
  },
})

const searchDep: any = useAttrs()['search-dep']

const _state = reactive({
  queryForm: {
    name: '',
  },
  form: {
    oid: props.oid,
    upper: props.dep.did,
    name: '',
    contact: '',
    contactPhone: '',
    remark: '',
    tier: 0,
    enable: true,
  },
})
const { queryForm } = toRefs(_state)

const tableHeight = ref(130)
const setTableHeight = () => {
  nextTick(() => {
    const options = {
      root: '#level-content',
      elements: [
        '#level-content .el-tabs__header',
        '#level-content .dep-search',
        '#level-content .dep-page',
      ],
      otherFunc: () => {
        const tablewrapPaddingTop = parseFloat(
          getStyle('#level-content .table-wrap')?.paddingTop || 0
        )
        const tablewrapPaddingtBottom = parseFloat(
          getStyle('#level-content .table-wrap')?.paddingBottom || 0
        )

        return tablewrapPaddingTop + tablewrapPaddingtBottom
      },
    }
    const { root, elements, otherFunc } = options
    const rootH = (document.querySelector(root) as HTMLElement)?.offsetHeight || 0
    let elementH = 0
    elements.forEach((ele) => {
      elementH += (document.querySelector(ele) as HTMLElement)?.offsetHeight || 0
    })
    const otherH = otherFunc()
    tableHeight.value = rootH - elementH - otherH
  })
}

const search = () => {
  handleSearch(DepApi.getDepByPage, {
    ...queryForm.value,
    upper: props.dep.did,
    oid: props.oid,
  })
}

const create = () => {
  _state.form.upper = props.dep.did
  handleAdd('创建科室部门')
}

const changeStatus = async (row: IBaseObj) => {
  let msg = ''
  let successMsg = ''
  if (!row.enable) {
    msg = `确认禁用部门${row.name}`
    successMsg = '禁用成功'
  } else {
    msg = `确认启用部门${row.name}`
    successMsg = '启用成功'
  }

  ElMessageBox.confirm(msg, '系统提示', {
    showClose: false,
  })
    .then(async () => {
      const ret = await DepApi.updateStatus({
        did: row.did,
        enable: row.enable,
      })
      if (ret.data) {
        ElMessage({ message: successMsg, type: 'success' })
        search()
      }
    })
    .catch(() => {
      row.enable = !row.enable
    })
}

const editInit = async (row: IBaseObj) => {
  const ret = await DepApi.getDepById(row.did)
  if (ret.data) {
    handleEdit('修改科室部门')
    _state.form = ret.data
  }
}

const del = (row: IBaseObj) => {
  handleDelete({
    url: DepApi.delUrl,
    id: row.did,
    message: '此操作将永久删除该科室部门，是否继续?',
    success: () => {
      search()
      searchDep()
    },
  })
}
const formWrapper = ref()
const addOrEditReset = () => {
  formWrapper.value.clear()
  _state.form = {
    oid: props.oid,
    upper: props.dep.did,
    name: '',
    contact: '',
    contactPhone: '',
    remark: '',
    tier: 0,
    enable: true,
  }
}

const closeDrawer = () => {
  state.isAdd = true
  addOrEditReset()
}

const confirm = () => {
  handleClose()
  search()
  searchDep()
}

defineExpose({
  search,
  setTableHeight,
})
</script>

<style lang="scss" scoped>
.search-wrap {
  justify-content: space-between !important;
}

.table-wrap {
  flex: 1;
}
</style>
